package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallBannerMapper;
import org.linlinjava.litemall.db.domain.LitemallAd;
import org.linlinjava.litemall.db.domain.LitemallAdExample;
import org.linlinjava.litemall.db.domain.LitemallBanner;
import org.linlinjava.litemall.db.domain.LitemallBannerExample;
import org.linlinjava.litemall.db.util.DateUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class BannerService {

    @Resource
    private LitemallBannerMapper bannerMapper;

    public List<LitemallBanner> queryIndex() {
        LitemallBannerExample example = new LitemallBannerExample();
        String currentTime = DateUtil.currentTime();
        example.or().andDeletedEqualTo(false).andTimeLE(currentTime).bannerTimeGE(currentTime);
        return bannerMapper.selectByExample(example);
    }

    public List<LitemallBanner> querySelective(String name, String content, Integer page, Integer limit, String sort, String order) {
        LitemallBannerExample bannerExample = new LitemallBannerExample();
        LitemallBannerExample.Criteria criteria = bannerExample.createCriteria();

        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            bannerExample.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return bannerMapper.selectByExample(bannerExample);
    }

    public int updateById(LitemallBanner banner) {
        banner.setUpdateTime(LocalDateTime.now());
        return bannerMapper.updateByPrimaryKeySelective(banner);
    }

    public void deleteById(Integer id) {
        bannerMapper.logicalDeleteByPrimaryKey(id);
    }

    public void add(LitemallBanner banner) {
        banner.setUpdateTime(LocalDateTime.now());
        bannerMapper.insertSelective(banner);
    }

    public LitemallBanner findById(Integer id) {
        return bannerMapper.selectByPrimaryKey(id);
    }
}
